package com.ecp.ws.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignTool {
	/**
	 * 计算签名
	 * @param params
	 * @param key 秘钥
	 * @return
	 */
	public static String sign(Map<String,String> params, String key) {
		String sign = "";
		try {
			 sign = MD5(URLEncoder.encode(getSign(params, key), "UTF-8").toUpperCase());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sign;
	}


	/**
	 * 参数名排序，并拼接key值
	 * @param params
	 * @param privateKey
	 * @return
	 */
	public static String getSign(Map params, String privateKey) {
		List keys = new ArrayList(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = (String) params.get(key);
			if (i == keys.size() - 1) {
				prestr = prestr + value;
			} else {
				prestr = prestr + value;
			}
		}
		return prestr + privateKey;
	}
	
	/**
	 * MD5加密
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
//		System.out.println("转码后MD5加密前 :"+s);
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
//			System.out.println("MD5加密后："+new String(str));
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
}
